<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Api;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Request;
use Hyperf\View\RenderInterface;
use Illuminate\Support\Facades\Hash;
class OrdersController
{

     /*
      *
      * 添加签订合同
      *
      *order_id
      * */

     public function upload_agreement(Request $request){

         if(isset($request->agreement_pic)) {
             $filename = $this->image('agreement_pic', $request);
             $pic_id = DB::table('agreement_pic')
                 ->insertGetId(array(
                     'name'=>$filename,'make_date'=>$request->make_date,
                     'agreement_address'=>$request->agreement_address,
                     'pay_company'=>$request->pay_company,
                     'get_company'=>$request->get_company
                 ));
             $agreement = DB::table('agreement')
                 ->where('id',$request->agreement_id)
                 ->select('id','get_company','supplyer_company','agreement_position','pic_id','create_date')->first();
             $pic = $agreement->pic_id.$pic_id.',';
             DB::table('agreement')->where('id',$agreement->id)->update(array('pic_id'=>$pic));

             $data['make_date'] = $agreement->create_date;
             $data['agreement_address'] = $agreement->agreement_position;
             $data['pay_company'] = $agreement->supplyer_company;
             $data['get_company'] = $agreement->get_company;

                $res['status'] = true;
                $res['code'] = 200;
                $res['msg'] = '上传成功';
                $res['data']  = $data;
                return json_encode($res,1);

         }else{

                $res['status'] = false;
                $res['code'] = 400;
                $res['msg'] = '上传失败';
                $res['data']  = [];
                return json_encode($res,1);


         }

     }

     /*
      * 查看已经签订合同
      * */

     public function agreement(Request $request)
     {
         $agreement = DB::table('agreement')
             ->select('id', 'sign_agreement_id', 'order_product_id')
             ->where('id', $request->agreement_id)->first();

         $order_product_id = explode(',', $agreement->order_product_id);
         if (!empty($order_product_id)) {
             $order_product = DB::table('order_product')
                 ->select('id', 'brand', 'standards', 'product_address', 'price', 'product_num', 'total_sell', 'mark')
                 ->where('servicer_id', $_SESSION['servicer_id'])
                 ->whereIn('id', $order_product_id)->get();


             $sign_agreement = DB::table('sign_agreement')->where('id', $agreement->sign_agreement_id)->first();

             if (!empty($sign_agreement)) {
                 $res['status'] = true;
                 $res['code'] = 200;
                 $res['msg'] = '';
                 $res['data'] = (array)$sign_agreement;
                 $res['data']['product'] = $order_product;
                 return json_encode($res, 1);
             } else {
                 $res['status'] = false;
                 $res['code'] = 400;
                 $res['msg'] = '没有数据';
                 $res['data'] = [];
                 return json_encode($res, 1);
             }
         }
     }



      /*
      * servicer_id
      *
      * return json
      * */


     public function servicer_order(){
        $info = DB::table('order')
            ->select('id','order_product_id','servicer_name','customer_phone','pay_address',
                'take_name','take_phone','get_address','standards','product_num','brand','company_name',
                'pay_address','servicer_phone','status','preget','code','create_time')
            ->where('servicer_id',$_SESSION['servicer_id'])
            ->get();
		$info = json_decode($info);

        $res['status'] = true;
        $res['code'] = 200;
  	    $res['msg'] = '';
  	    $res['data'] =$info;
		return json_encode($res,1);

     }


     /*
      * servicer_id
      *
      * return json
      * */


     public function success_order(){
        $info = DB::table('order')
            ->select('id','order_product_id','servicer_name',
                'take_name','take_phone','get_address','standards','product_num','brand','company_name',
                'pay_address','servicer_phone','status','preget','code','create_time','note_pic','coupon_pic')
            ->where('servicer_id',$_SESSION['servicer_id'])
            ->where('status',1)
            ->where('code',1)
            ->get();
        if(!empty($info)) {
            $info = json_decode($info,1);
            foreach ($info as $key=>$value){
            if(!empty($value['note_pic'])) {
                $info[$key]['coupon'][] = $_SESSION['network'] . $_SERVER['SERVER_NAME'] . '/image/' . $value['note_pic'];
            }
            if(!empty($value['coupon_pic'])) {
                $info[$key]['coupon'][] = $_SESSION['network'] . $_SERVER['SERVER_NAME'] . '/image/' . $value['coupon_pic'];
            }
            unset( $info[$key]['note_pic']);
            unset( $info[$key]['coupon_pic']);
          }

            $res['status'] = true;
            $res['code'] = 200;
            $res['msg'] = '';
            $res['data'] = $info;
            return json_encode($res, 1);
        }else{
            $res['status'] = true;
            $res['code'] = 200;
            $res['msg'] = '';
            $res['data'] = [];
            return json_encode($res, 1);
        }

     }




     /*
      * 客户回款
      *customer_name
      * */

     public function customer_back(Request $request){

        $customer = DB::table('customer')
               ->select('id','customer_name','balance')
               ->where('servicer_id',$_SESSION['servicer_id'])
               ->where('status',0)
               ->get();

           $customer_id = [];
           $customer_balance = [];
           $customer_name = [];
           $customer = json_decode($customer,1);
           foreach ($customer as $key=>$value){
                $customer_id[] = $value['id'];
                $customer_balance[$value['id']] = $value['balance'];
                $customer_name[$value['id']] = $value['customer_name'];
           }

           $order = DB::table('order')->select('id','total_sell','customer_id')->whereIn('customer_id',$customer_id)->get();
           $order = json_decode($order,1);
           foreach ($order as $key=>$value){
                $customer_balance[$value['customer_id']] = (int)$customer_balance[$value['customer_id']] - (int)$value['total_sell'];
                $order[$key]['blance'] = $customer_balance[$value['customer_id']];
                $order[$key]['customer_name'] = $customer_name[$value['customer_id']];
           }
        $res['status'] = true;
        $res['code'] = 200;
  	    $res['msg'] = '';
  	    $res['data'] = $order;
        return json_encode($res,1);
     }


     /*
      * 汇款详情
      *
      * */
     public function pay_detail(Request $request){

         $order = DB::table('order')
             ->select('id','agreement_id','total_sell','already_pay','pay_id','product_num','pay_method','remarks')
             ->where('id',$request->order_id)
             ->first();

         $pay_id = explode(',',$order->pay_id);


         if(!empty($pay_id)) {

             try {
                 $pay = DB::table('pay')
                     ->select('proof_pic')
                     ->whereIn('id', $pay_id)
                     ->orderBy('create_time', 'asc')->get();

                 $data['proof_pic'] = [];
                 foreach ($pay as $key=>$value){
                     $data['proof_pic'][] = $_SESSION['network'].$_SERVER['SERVER_NAME'].'/pay/'.$value->proof_pic;
                 }

                 $pay_one = DB::table('pay')
                     ->select('balance', 'pay_method', 're_balance', 'customer_name', 'pay_money')
                     ->whereIn('id', $pay_id)
                     ->orderBy('create_time', 'asc')->first();

                 $pay_last = DB::table('pay')
                     ->select('balance', 'pay_method', 're_balance', 'customer_name', 'pay_money')
                     ->whereIn('id', $pay_id)
                     ->orderBy('create_time', 'desc')->first();
                 $data['agreement_id'] = $order->agreement_id;
                 $data['customer_name'] = $pay_one->customer_name;
                 $data['origin_blance'] = $pay_one->re_balance - $pay_one->pay_money;
                 $data['period_pay'] = $order->total_sell;
                 $data['period_get'] = $order->already_pay;
                 $data['period_blance'] = $pay_last->balance;
                 $data['period_sell'] = $order->product_num;
                 $data['pay_method'] = $order->pay_method;
                 $data['pay_mark'] = $order->remarks;

                 $res['status'] = true;
                 $res['code'] = 200;
                 $res['msg'] = '';
                 $res['data'] = $data;
                 return json_encode($res, 1);
             }catch (Exception $e){
                 $res['status'] = false;
                 $res['code'] = 400;
                 $res['msg'] = '没有填写支付信息';
                 $res['data'] = [];
                 return json_encode($res, 1);
             }
         }else{
             $res['status'] = false;
             $res['code'] = 400;
             $res['msg'] = '';
             $res['data'] = [];
             return json_encode($res, 1);
         }

     }

     /*
      * 支付汇总
      * */

     public function pay_all(Request $request){

            $order = DB::table('order')
                ->where('id',$request->order_id)
                ->select('pay_id','already_pay')->first();
            $pay_id = explode(',',$order->pay_id);
            if(!empty($pay_id)){
                $pay = DB::table('pay')
                    ->select('pay_money','proof_pic','create_date')
                    ->whereIn('id',$pay_id)->get();
                $data = [];
                //$data['already_pay'] = $order->already_pay;
                foreach ($pay as $key=>$value){
                    $data[$key]['period_pay'] = $value->pay_money;
                    $data[$key]['proof_pic'] = $_SESSION['network'].$_SERVER['SERVER_NAME'].'/pay/'.$value->proof_pic;
                    $data[$key]['date'] = $value->create_date;
                }
             $res['status'] = true;
             $res['code'] = 200;
             $res['msg'] = '';
             $res['data'] = $data;
             return json_encode($res, 1);
            }else{
             $res['status'] = false;
             $res['code'] = 400;
             $res['msg'] = '';
             $res['data'] = [];
             return json_encode($res, 1);
            }
     }


     /*
      * 添加支付信息
      * */
     public function pay_info(Request $request){
           // Log::debug($request->all());
            if(isset($request->pay_pic)&&(int)$request->pay_money > 0) {
                $filename = $this->image('pay_pic', $request);
                $customer = DB::table('customer')
                    ->select('id','customer_name','balance')
                    ->where('id',$request->customer_id)->first();
                $pay_money = $request->pay_money;
                $money = $customer->balance + $pay_money;

                $order = DB::table('order')
                    ->select('id','total_sell','already_pay','pay_id','pay_status')
                    ->where('id',$request->order_id)->first();

                if($order->pay_status == 1){
                    $res['status'] = false;
                    $res['code'] = 400;
                    $res['msg'] = '你已经提交付款完了';
                    $res['data']  = [];
                    return response()->json($res);
                }

                $balance = $money - $order->total_sell + $order->already_pay;
                DB::table('customer')->where('id',$request->customer_id)->update(array('balance'=>$balance));

                $pay['customer_id'] = $customer->id;
                $pay['customer_name'] = $customer->customer_name;
                $pay['balance'] = $balance;
                $pay['re_balance'] = $money;
                $pay['proof_pic'] = $filename;
                $pay['pay_money'] = $request->pay_money;
                $pay['date'] = $request->pay_date;
                $pay['pay_method'] = $request->pay_method;
                $pay['get_company'] = $request->get_company;
                $pay['order_id'] = $request->order_id;
                $pay['create_time'] = time();
                $pay['create_date'] = date('Y-m-d H:i:s',time());
                $pay_id = DB::table('pay')->insertGetId($pay);
                if($money > $order->total_sell){
                    $pay_status = 1;
                    $already_pay = $order->total_sell;
                    $order_data['pay_status'] =$pay_status;
                }else{
                    $already_pay = $money;
                }

                $order_data['pay_id'] = $order->pay_id.$pay_id.',';
                $order_data['already_pay'] =$already_pay;
                DB::table('order')->where('id',$request->order_id)->update($order_data);

                $res['status'] = true;
                $res['code'] = 200;
                $res['msg'] = '';
                $res['data'] = [];
                return json_encode($res);
            }else{

                $res['status'] = false;
                $res['code'] = 400;
                $res['msg'] = '';
                $res['data'] = [];
                return json_encode($res);

            }

     }

     public function delivery_note(Request $request){


            $res['data']['note_pic'] = 'http://dz.gdweihu.com/product/056dde470d0986b18d90452d0f04e73.png';
            $res['data']['coupon_pic'] = 'http://dz.gdweihu.com/product/056dde470d0986b18d90452d0f04e73.png';

            $res['status'] = true;
            $res['code'] = 200;
            $res['msg'] = '';

            return json_encode($res,1);

     }


     public function overdue(Request $request){

                //提醒后多久又提
                $alert_date = date('Y-m-d H:i:s',strtotime('+4 days'));
                $order = DB::table('order')
                ->select('id','customer_name','pay_method','total_sell','already_pay','arriver_date','alert_time')
                ->where('pay_status',0)
                ->where('arriver_date','<',$alert_date)
                ->where('servicer_id',$_SESSION['servicer_id'])
                ->get();

                $pay = [];

                foreach ($order as $key=>$value){
                        if($value->alert_time < time() ){
                       $pay[$key]['alert_code'] = 1;
                       }else{
                       $pay[$key]['alert_code'] = 0;
                       }
                        $pay[$key]['blance']  = $value->total_sell - $value->already_pay;
                        $pay[$key]['order_id'] =$value->id;
                        $pay[$key]['customer_name'] =$value->customer_name;
                        $pay[$key]['pay_method'] =$value->pay_method;
                        $pay[$key]['expire'] = 4;
                }

            $res['status'] = true;
            $res['code'] = 200;
            $res['msg'] = '';
            $res['data'] = $pay;

            return json_encode($res,1);

     }

     /*
      * 轮询提醒
      * */

     public function alert_code(){

            //提醒后多久又提
                $alert_date = date('Y-m-d H:i:s',strtotime('+4 days'));
                $order = DB::table('order')
                ->select('id','customer_name','pay_method','total_sell','already_pay','arriver_date','alert_time')
                ->where('pay_status',0)
                ->where('arriver_date','<',$alert_date)
                ->where('servicer_id',$_SESSION['servicer_id'])
                ->get();

                $pay = [];

                foreach ($order as $key=>$value){
                        if($value->alert_time < time() ){
                       $pay[$key] = 1;
                       }else{
                       $pay[$key] = 0;
                       }
                }

            $res['status'] = true;
            $res['code'] = 200;
            $res['msg'] = '';
            $res['data'] = $pay;

            return json_encode($res,1);
     }







     /*
      * 订单详细
      * */


     public function order_detail(Request $request){
             $info = DB::table('order')
                 ->select('id','driver_id','driver_status','order_code','driver_name','order_product_id','product_id','brand',
                'category','standards','product_num','servicer_name','servicer_phone','take_name','take_phone','get_position','get_address',
                'make_date','pay_address','supplyer_company','company_name','end_time','car_team','car_info','car_num','remarks','code','print_status'
                 )
                 ->where('id',$request->order_id)
                 ->where('servicer_id',$_SESSION['servicer_id'])
                 ->first();

             $product_id = explode(',',$info->order_product_id);
             $order_product= DB::table('order_product')
                 ->select('product_name','standards','brand','category','product_num','pack_method')
                 ->whereIn('id',$product_id)
                 ->get();

            $info = (array)$info;
            $res['status'] = true;
            $res['code'] = 200;
            $res['msg'] = '';
            $res['data']['product'] = $order_product;
            $res['data']['info'] =$info;
            return json_encode($res,1);

     }




     public function overdue_alert(Request $request){

              $alert_time  = strtotime('+4 hours');

               $order = DB::table('order')
                   ->select('id','total_sell','already_pay','arriver_date','alert_time')
                   ->where('id',$request->order_id)
                   ->first();
               if($order->alert_time < time() ){
                   $data['alert_code'] = 1;
                   DB::table('order')
                       ->where('id',$request->order_id)
                       ->update(array('alert_time'=>$alert_time));
               }else{
                   $data['alert_code'] = 0;
               }

               $account_time = strtotime($order->arriver_date)+4*24*60*60;
               $account_date = date('Y.m.d',$account_time);
               $data['expire'] = 4;
               $data['account_date'] = $account_date;
               $data['overdue_time'] = round((time() - $account_time)/3600/24);
               $data['overdue_money'] = $order->total_sell - $order->already_pay;

                $res['status'] = true;
                $res['code'] = 200;
                $res['msg'] = '';
                $res['data'] = $data;
            return json_encode($res,1);
     }


     /*
      * 添加跟单业务员
      * */
     public function order_service_add(Request $request){

         if(isset($request->name)&&isset($request->telephone)){
             $servicer = DB::table('servicer')
                    ->select('id')
                    ->where('name',$request->name)
                    ->where('telephone',$request->telephone)->first();
             if($servicer){
             $order = DB::table('order')->select('order_servicer')->where('id',$request->order_id)->first();
             $order_servicer = $order->order_servicer.$servicer->id.',';
             DB::table('order')->where('id',$request->order_id)->update(array('order_servicer'=>$order_servicer));
                $res['status'] = true;
                $res['code'] = 200;
                $res['msg'] = '';
                $res['data'] = [];
             }else{
                $res['status'] = false;
                $res['code'] = 400;
                $res['msg'] = '';
                $res['data'] = [];
             }

             return json_encode($res,1);
         }
     }





     /*
      * 查看跟单业务员
      * */
     public function order_service(Request $request){

        $order = DB::table('order')->select('servicer_id','order_servicer')->where('id',$request->order_id)->first();
        if(!empty($order)) {
            $servicer_id = explode(',', $order->order_servicer);
            if($_SESSION['servicer_id'] != $order->servicer_id){
                   $servicer_id[] = $order->servicer_id;
            }
            $servicer = DB::table('servicer')
                ->select('name', 'face_url', 'telephone', 'nikename')
                ->whereIn('id', $servicer_id)->get();

            $servicer = json_decode($servicer, 1);
            foreach ($servicer as $key => $value) {
                $servicer[$key]['face_url'] = $_SESSION['network'] . $_SERVER['SERVER_NAME'] . '/face_url/' . $value['face_url'];
            }

            $res['status'] = true;
            $res['code'] = 200;
            $res['msg'] = '';
            $res['data'] = $servicer;
            return json_encode($res, 1);
        }else{

            $res['status'] = false;
            $res['code'] = 400;
            $res['msg'] = '';
            $res['data'] = [];
            return json_encode($res, 1);

        }

     }




     /*
      * 逾期原因
      * */

     public function overdue_detail(Request $request){


              $order = DB::table('order')
                   ->select('id','total_sell','already_pay','arriver_date','alert_time','overdue_reason','pay_method','customer_name')
                   ->where('id',$request->order_id)
                   ->first();

               $account_time = strtotime($order->arriver_date)+4*24*60*60;
               $account_date = date('Y.m.d',$account_time);
               $data['customer_name'] = $order->customer_name;
               $data['total_sell'] = $order->total_sell;
               $data['overdue_time'] = round((time() - $account_time)/3600/24);

               $data['pay_method'] = $order->pay_method;
               $data['expire'] = 4;
               $data['account_date'] = $account_date;
               $data['overdue_money'] = $order->total_sell - $order->already_pay;
               $data['overdue_reason'] = $order->overdue_reason;

                $res['status'] = true;
                $res['code'] = 200;
                $res['msg'] = '';
                $res['data'] = $data;
            return json_encode($res,1);


     }



         //return string
    public function image($field,$request){
            $file = $request->file($field);//接前台图片
            if($file->getmimeType() == "image/png" || $file->getmimeType() == "image/jpeg"){
                $extension = $file->extension();//图片路径
                $name = date('YmdHis',time()).rand(00000000,99999999999).'.'.$extension;
                $file->move("./pay",$name);//移动至框架图片文件夹
                return $name;
            }
    }

     /*
      * 未付款原因
      *reason_text
      * */

     public function overdue_reason(Request $request){
            $alert_time  = strtotime('+4 hours');
            DB::table('order')->where('id',$request->order_id)->update(array('overdue_reason'=>$request->overdue_reason,'alert_time'=>$alert_time));
            $res['status'] = true;
            $res['code'] = 200;
            $res['msg'] = '';
            $res['data'] = [];
            return json_encode($res,1);

     }




}